package com.hrzyit.base.utils

import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.media.MediaPlayer.OnCompletionListener
import android.os.Build

/**
 * 音频播放管理
 */
object MediaManager {

    private var mMediaPlayer: MediaPlayer? = null
    private var isPause: Boolean = false

    /**
     * 播放音乐
     *
     * @param filePath
     * @param onCompletionListener
     */
    fun playSound(filePath: String, onCompletionListener: OnCompletionListener) {
        if (mMediaPlayer == null) {
            mMediaPlayer = MediaPlayer()

            //设置一个error监听器
            mMediaPlayer!!.setOnErrorListener { _, _, _ ->
                mMediaPlayer!!.reset()
                false
            }
        } else {
            mMediaPlayer!!.reset()
        }
        try {
            if (Build.VERSION.SDK_INT >= 21) {
                val audioAttributes = AudioAttributes.Builder()
                    .setLegacyStreamType(AudioManager.STREAM_MUSIC).build()

                mMediaPlayer!!.setAudioAttributes(audioAttributes)
            } else {
                mMediaPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC)
            }

            mMediaPlayer!!.setOnCompletionListener(onCompletionListener)
            mMediaPlayer!!.setDataSource(filePath)
            mMediaPlayer!!.prepare()
            mMediaPlayer!!.start()
        } catch (e: Exception) {

        }

    }

    /**
     * 暂停播放
     */
    fun pause() {
        if (mMediaPlayer != null && mMediaPlayer!!.isPlaying) { //正在播放的时候
            mMediaPlayer!!.pause()
            isPause = true
        }
    }

    /**
     * 当前是isPause状态
     */
    fun resume() {
        if (mMediaPlayer != null && isPause) {
            mMediaPlayer!!.start()
            isPause = false
        }
    }

    /**
     * 释放资源
     */
    fun release() {
        if (mMediaPlayer != null) {
            mMediaPlayer!!.release()
            mMediaPlayer = null
        }
    }
}
